<?php
namespace Addons\CusManage\Controller\Admin;

use Models\BaseModel as Model;
use Session;
use Addons\CusManage\Helper;
use Addons\QyWechat\Helper as Helpers;
use Addons\QyWechat\Helper as QyHelper;
use Addons\CusManage\Controller\Admin\BaseAdmin;


/**
 * 客户阶段管理
 */
class CusManage extends BaseAdmin
{
	/**
	*列表页
	*/
	public function clmanage(){
		$wid = Session::get('wid');
		$name = $_GET['name'];
		$where = [];
		$where['wid'] = $wid;
		$where['status'] = 0; 
		$where['level_manager_id@>'] = 0;
		$h = Helpers::getInstance(); 
		$r_user_id_arr = $h->get_check_range('cuscontact_clmanage');
		if($r_user_id_arr){
			$where['user_id'] = $r_user_id_arr;
		}
		$p = new \Pagination();		
		$externalcontact_list =  $p->model_list((new Model('qy_externalcontact_list'))->where($where));
		foreach ($externalcontact_list as $keye => $contact_list) {
			$externalcontact_list[$keye]->et_tagss = json_decode($contact_list->tags,1);
			$qYuser = $h->get_user_by_id($wid,$contact_list->user_id);
			$lastChat = (new Model('qy_chat_data'))->where(['fromid'=>$qYuser['userid'],'tolist@~'=>$contact_list->external_userid])->max('msgtimes');
			$externalcontact_list[$keye]->lastchat = $lastChat;
		}
		unset($where['level_manager_id@>']);
		$where['level_manager_id'] = 0;
		$noset_externalcontact_list = (new Model('qy_externalcontact_list'))->where($where)->count();
		$time = time();
		$level_manager = (new Model('qy_level_manager'))->where(['wid'=>$wid])->order('sequence asc')->list_all();
		if(count($level_manager) == 0){
			$sql = "INSERT INTO qvmh_qy_level_manager (wid,name,sequence,description,qyuser_remind_status,qyuser_remind_type,remind_exptime_d,remind_exptime_h,ctime,utime) values ($wid,'新加客户',1,'新加客户',0,1,7,'09:00',$time,$time),($wid,'初步沟通',2,'初步沟通',0,1,7,'09:00',$time,$time),($wid,'意向客户',3,'意向客户',0,1,7,'09:00',$time,$time),($wid,'即将成交',4,'即将成交',0,1,7,'09:00',$time,$time),($wid,'已付款客户',5,'已付款客户',0,1,7,'09:00',$time,$time)";
			db_query($sql);
			$level_manager = (new Model('qy_level_manager'))->where(['wid'=>$wid])->order('sequence asc')->list_all();
		}
		foreach ($level_manager as $keyl => $manager) {
			$where['level_manager_id'] = $manager->id;
			$user_data = (new Model('qy_externalcontact_list'))->where($where)->order("id asc")->limit(0,5)->list_all();
			foreach ($user_data as $keye => $contact_list) {
				$user_data[$keye]->et_tagss = json_decode($contact_list->tags,1);
				$qYuser = $h->get_user_by_id($wid,$contact_list->user_id);
				$lastChat = (new Model('qy_chat_data'))->where(['fromid'=>$qYuser['userid'],'tolist@~'=>$contact_list->external_userid])->max('msgtimes');
				$user_data[$keye]->lastchat = $lastChat;
			}
			$level_manager[$keyl]->user_data = $user_data;
			$level_manager[$keyl]->count_num = count($user_data);
		}
		$tagArr = $h->get_et_tags($wid);

		$eTags = (new Model('qy_externalcontact_tag'))->field("group_name,tags")->where(['wid'=>$wid])->list_all();
		foreach($eTags as $k=>$v){
			$eTags[$k]->etags = json_decode($v->tags,1);
		}
		$bh = Helper::getInstance();
		if($_SERVER['REQUEST_URI'] != "Addons/CusManage/Admin/CusManage/clmanage.html"){
			$this->assign('type',2);
		}
		$GLOBALS['P']->firstlink = "/Addons/CusManage/Admin/CusManage/clmanage_1.html";
		$GLOBALS['P']->prevlink = "/Addons/CusManage/Admin/CusManage/clmanage_1.html";
		$this->assign('h',$h);
		$this->assign("p", $p);
		$this->assign("P", $GLOBALS['P']);
		$this->assign('bh',$bh);
		$this->assign('name',$name);
		$this->assign('tagArr',$tagArr);
		$this->assign('eTags',$eTags);
		$this->assign('level_manager',$level_manager);
		$this->assign('externalcontact_list',$externalcontact_list);
		$this->assign('noset_externalcontact_list',$noset_externalcontact_list);
		return $this->show();
	}

	/**
	*分页
	*/
	public function pages(){
		setApi();
		$wid = Session::get('wid');
		$where['level_manager_id'] = $_POST["id"];
		$where['wid'] = $wid;
		$where['status'] = 0;
		$limit = $_POST["page"]*5;
		$user_data = (new Model('qy_externalcontact_list'))->where($where)->order("id asc")->limit($limit,5)->list_all();
		$h = QyHelper::getInstance();
		$tagArr = $h->get_et_tags($wid);
		foreach ($user_data as $key => $value) {
			$tag = json_decode($value->tags,1);
			if(count($tag)){
				foreach ($tag as $values) {
					$tsgs[] = $tagArr[$values];
				}
				$user_data[$key]->tags = $tsgs;
			}else{
				$user_data[$key]->tags = array();
			}
			$qYuser = $h->get_user_by_id($wid,$value->user_id);
			$user_data[$key]->ex_name = $qYuser['name'];
			$lastChat = (new Model('qy_chat_data'))->where(['fromid'=>$qYuser['userid'],'tolist@~'=>$value->external_userid])->max('msgtimes');
			$user_data[$key]->lastchat = $lastChat;
			if(!$value->lastchat){
				$user_data[$key]->lastchat = date("Y-m-d H:i:s");
			}
		}
		$level_manager = (new Model('qy_level_manager'))->find($_POST["id"]);
		if(count($user_data)){
			sendSuccess("获取成功",[$user_data,$level_manager]);
		}sendError("获取失败");
	}
	/**
	* 获取未分配客户列表
	*/
	public function get_noset_ex(){
		$wid = Session::get('wid');
		setApi();
		$name = $_GET['name'];
		$where = [];
		$where['wid'] = $wid;
		$where['status'] = 0;
		$where['level_manager_id'] = 0;
		$h = Helpers::getInstance(); 
		$r_user_id_arr = $h->get_check_range('cuscontact_clmanage');
		if($r_user_id_arr){
			$where['user_id'] = $r_user_id_arr;
		}
		if(trim($name)!=''){
			$where['name@~'] = $name;
		}
		$searchTag = $_GET['searchTag'];

		$users =  (new Model('qy_user_list'))->field('id,name')->where(['wid'=>$wid])->list_all_array();
		foreach ($users as $k => $v) {
			$users[$v['id']] = $v;
		}
		$pageIndex = $_GET['page'] ?: 1;
		$pageSize = $_GET['limit'] ?: 10;
		$lim = 	$pageSize*($pageIndex-1).','.$pageSize;
		$count = (new Model('qy_externalcontact_list'))->field('id,name,tags,avatar,user_id,createtime')->where($where)->count();
		$noset_externalcontact_list = (new Model('qy_externalcontact_list'))->field('id,name,tags,avatar,user_id,createtime')->where($where)->limit($lim)->list_all_array();
		$h = QyHelper::getInstance();
		$tagArr = $h->get_et_tags($wid);
		
		foreach ($noset_externalcontact_list as $key => $value) {
			$noset_externalcontact_list[$key]['createtime'] = date("Y-m-d H:i:s",$value['createtime']);
			$noset_externalcontact_list[$key]['user_id'] = $users[$value['user_id']]['name'];
			$tag_arr = [];
			foreach (json_decode($value['tags'],1) as $tag) {
				$tag_arr[] = $tagArr[$tag];
			}
			$noset_externalcontact_list[$key]['tags'] = $tag_arr?implode(',', $tag_arr):'-';
		}

    	sendResponse(['code' => 0, 'msg' => '','count' => $count, 'data' => $noset_externalcontact_list, 'page'=>$pageIndex], true);
		// sendSuccess('数据',$noset_externalcontact_list);
	}
	/**
	* 分配客户阶段
	*/
	public function set_cus_manage(){
		// echo date("H:i:s").'<br>';
		$wid = Session::get('wid');
		
		// if($searchTag){
		// 	$searchTagArr = explode(',', $searchTag);
		// 	$where['tags@~'] = $searchTagArr;
		// }
		// dump($where);die;
		$time = time();
		$level_manager = (new Model('qy_level_manager'))->where(['wid'=>$wid])->order('sequence asc')->list_all();
		// $noset_externalcontact_list = (new Model('qy_externalcontact_list'))->field('id,wid,name,tags,avatar,user_id,createtime')->where(['wid'=>$wid, 'status'=>0,'level_manager_id'=>0])->list_all_array();
		// foreach ($noset_externalcontact_list as $keyn => $noset_et) {
		// 	$noset_externalcontact_list[$keyn]->et_tags = json_decode($noset_et->tags,1);
		// }
		$h = QyHelper::getInstance();
		$tagArr = $h->get_et_tags($wid);
		$eTags = (new Model('qy_externalcontact_tag'))->where(['wid'=>$wid])->list_all();
		foreach($eTags as $k=>$v){
			$eTags[$k]->etags = json_decode($v->tags,1);
		}
		$bh = Helper::getInstance();
		$this->assign('h',$h);
		$this->assign('bh',$bh);
		$this->assign('name',$name);
		$this->assign('tagArr',$tagArr);
		$this->assign('eTags',$eTags);
		$this->assign('level_manager',$level_manager);
		// $this->assign('noset_externalcontact_list',$noset_externalcontact_list);
		// echo date("H:i:s").'<br>';
		// die;
		return $this->show();
	}
	/**
	*修改客户阶段
	*/
	public function update_level_manager(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['external_id'];
		$sequence = $_POST['clientStatus'];
		$id_arr = explode(',', $id);
		if(!count($id_arr)){
			sendError('至少选择一个客户');
		};
		$level_manager = (new Model('qy_level_manager'))->find(['wid'=>$wid,'sequence'=>$sequence]);
		$external = (new Model('qy_externalcontact_list'))->update(['id'=>$id_arr],['level_manager_id'=>$level_manager->id]);
		if($external){
			$sql = 'INSERT INTO qvmh_qy_levmanager_record (externalcontact_id,level_manager_id,status,ctime) values';
			$add_val = [];
			$time = time();
			foreach ($id_arr as $user_id) {
				$add_val[] = "($user_id,$level_manager->id,0,$time)";
			}
			$sql .= implode(',', $add_val);
			db_query($sql);
			sendSuccess('操作成功');
		}
		sendError('操作失败,请重新操作');
	}

	/**
	*客户阶段类型页列表
	*/
	public function setting(){
		$wid = Session::get('wid');		
		$level_manager = (new Model('qy_level_manager'))->where(['wid'=>$wid])->order('sequence asc')->list_all();
		$this->assign('level_manager',$level_manager);
		return $this->show();
	}
	
	/**
	*编辑客户阶段类型
	*/
	public function setting_save(){
		setApi();
		$wid = Session::get('wid');
		$level_manager = new Model('qy_level_manager');
		if($_POST['id']){
			$level_manager->find($_POST['id']);
		}else{
		    $total_manager = (new Model('qy_level_manager'))->where(['wid'=>$wid])->count();
    		if($total_manager >= 8){
    			sendError('最大可设置8个阶段');
    		}
			$level_manager->ctime = time();
			$level_manager->sequence = $total_manager + 1;
		}
		$level_manager->wid = $wid;
		$level_manager->name = $_POST['name'];
		$level_manager->description = $_POST['description'];
		$level_manager->qyuser_remind_status = $_POST['qyuser_remind_status'] ?? 0;
		$level_manager->qyuser_remind_type = $_POST['qyuser_remind_type'];
		$level_manager->remind_exptime_d = $_POST['remind_exptime_d'];
		$level_manager->remind_exptime_h = $_POST['remind_exptime_h'];
		$level_manager->utime = time();
		
		if($level_manager->save()){
			sendSuccess('操作成功',$level_manager->id);
		}
		sendError('操作失败,请重新操作');
	}

	/**
	*删除客户阶段
	*/
	public function del_manager(){
		setApi();
		$wid = Session::get('wid');
		$id = $_POST['id'];
		$count = (new Model('qy_externalcontact_list'))->where(['wid'=>$wid, 'level_manager_id'=>$id])->count();
		if($count>0){
			sendError('操作失败',$count);
		}
		$level_manager = (new Model('qy_level_manager'))->find($id);
		$sequence_a = $level_manager->sequence;
		$level_manager->remove();
		$level_managers = (new Model('qy_level_manager'))->where(['wid'=>$wid])->order('sequence asc')->list_all_array();
		$level_managers_count = count($level_managers);
		if($level_managers_count > 0){
			foreach ($level_managers as $key => $managers) {
				if($managers['sequence'] > $sequence_a){
					$manager = (new Model('qy_level_manager'))->find($managers['id']);
					$manager->sequence = $manager->sequence - 1;
					$manager->utime = time();
					$aa = $manager->save();
				}
			}
		}
		
		sendSuccess('操作成功');
	}

	/**
	*阶段设置上下移动
	*/
	public function move_sequence(){
		setApi();
		$id = $_POST['id'];
		if(!$id) sendError('移动失败');
		$direction = $_POST['direction'];
		$level_manager = (new Model('qy_level_manager'))->find($id);
		$wid = $level_manager->wid;

		if($direction == 'up'){
			if($level_manager->sequence == 1){
				sendError('首行不能上升移动');
			}
			$n_sequence = $level_manager->sequence - 1;
			$y_level_manager = (new Model('qy_level_manager'))->find(['wid'=>$wid,'sequence'=>$n_sequence]);
			$y_level_manager->sequence = $n_sequence + 1;
			$y_level_manager->save();

			$level_manager->sequence = $n_sequence;
			$level_manager->save();
			sendSuccess('操作成功');
		}else if($direction == 'down'){
			$max =  (new Model('qy_level_manager'))->where(['wid'=>$wid])->max('sequence');
			if($level_manager->sequence == $max){
				sendError('末行不能下降移动');
			}
			$n_sequence = $level_manager->sequence + 1;
			$y_level_manager = (new Model('qy_level_manager'))->find(['wid'=>$wid,'sequence'=>$n_sequence]);
			$y_level_manager->sequence = $n_sequence - 1;
			$y_level_manager->save();

			$level_manager->sequence = $n_sequence;
			$level_manager->save();
			sendSuccess('操作成功');
		}
		sendError('移动失败');	
	}

	/**
	*下载
	*/
	public function downexcel(){
		$wid = Session::get('wid');
		require_once DOXCX_FRAME_PATH . '/fun/library/php-excel.class.php';

		$where['wid'] = $wid;
		$where['status'] = 0;
		$where['level_manager_id@>'] = 0;
		$externalcontact_list = (new Model('qy_externalcontact_list'))->where($where)->list_all();
		$bh = Helper::getInstance();
		$h = QyHelper::getInstance();
		$arr = [
        	0 => ['客户名称', '客户备注', '客户描述','客户阶段', '流失状态', '企业名称', '添加人', '添加时间', '上次对话时间 ','企业标签','个人标签','性别','电话','年龄','生日']
    	];
    	$i = 1;
    	foreach ($externalcontact_list as $key => $external) {
    		$arr[$i]['客户名称'] = $external->name;
    		$arr[$i]['客户备注'] = $external->remark;
    		$arr[$i]['客户描述'] = $external->description;
    		$arr[$i]['客户阶段'] = $bh->get_sequence_by_id($external->level_manager_id)['name'];
    		$arr[$i]['流失状态'] = $external->status == 0 ? '未流失' : '已流失';
    		$arr[$i]['企业名称'] = $external->type == 1 ? '微信用户': $external->corp_name;
    		$arr[$i]['添加人'] = $h->get_user_by_id($external->wid,$external->user_id)['name'];
    		$arr[$i]['添加时间'] = date('Y-m-d H:i:s',$external->createtime);
    		$arr[$i]['上次对话时间'] = '';
    		$arr[$i]['企业标签'] = '';
    		$arr[$i]['个人标签'] = $this->get_tag_str($external->tags);
    		$arr[$i]['性别'] = $external->gender == 1 ? '男性' : '女性';
    		$arr[$i]['电话'] = '';
    		$arr[$i]['年龄'] = '';
    		$arr[$i]['生日'] = '';
    		$i++;
    	}

    	$xls = new \Excel_XML('utf-8', false, '数据导出');
		$xls->addArray($arr);
		$xls->generateXML('qvmhcus'.date('Y-m-d H:i:s'),time());
		exit();
	}

	private function get_tag_str($tags){
		$h = QyHelper::getInstance();
		$arrTag = $h->get_et_tags($external->wid);
		$tags_arr = json_decode($tags,1);
		$arr_t = [];
		foreach ($tags_ar as $tag) {
			if(array_key_exists($tag,$arrTag)){
				$arr_t[] = $arrTag[$tag];
			}
		}

		return implode(',', $arr_t);
	}
	
}